package com.econ.powercloud.ems.timing.warn;

import com.econ.powercloud.common.base.facade.util.JacksonUtil;
import com.econ.powercloud.ems.aop.TimingRetryValid;
import com.econ.powercloud.ems.common.pojo.EmsWarnStatDTO;
import com.econ.powercloud.ems.dal.entity.EmsWarnStatistical;
import com.econ.powercloud.ems.service.dao.EmsWarnStatisticalDAO;
import com.econ.powercloud.ems.util.WarnCacheKeyUtils;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Author : zjf
 * @Description : 诊断预警定时任务
 * @Date : 2022/12/6 16:42
 * @Modified by : zjf
 */
@Component
public class WarnTask {

    public static final String METER_TASK = "ems-warn-zero-task";

    @Autowired
    private EmsWarnStatisticalDAO emsWarnStatisticalDAO;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 0点清除诊断预警统计的当日预警点号数量，当日预警次数
     */
    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional(rollbackFor = Throwable.class)
    @TimingRetryValid(lockName = METER_TASK)
    public void clearWarnEveryData(){
        List<EmsWarnStatistical> statisticalList = emsWarnStatisticalDAO.list();
        if(CollectionUtils.isEmpty(statisticalList)){
            return;
        }
        statisticalList.stream().forEach(d->{
            d.setWarnTodayPidNum(0);
            d.setWarnTodayNum(0);
        });
        emsWarnStatisticalDAO.updateBatchById(statisticalList);
        //预警统计redis更新
        String statKey = WarnCacheKeyUtils.getWarnStatKey();
        Map<String,String> statDTOMap = Maps.newHashMap();
        statisticalList.stream().forEach(d->{
            statDTOMap.put(d.getDeviceCode(), JacksonUtil.toJSONString(EmsWarnStatDTO.builder()
                    .id(d.getId()).deviceCode(d.getDeviceCode()).warnTotalNum(d.getWarnTotalNum()).warnTodayNum(d.getWarnTodayNum())
                    .pids(Collections.emptySet()).build()));
        });
        stringRedisTemplate.opsForHash().putAll(statKey,statDTOMap);
    }

}
